const dataBase = require('../../mysql')

const sql = require('../../mysql/sql')
const verify = require('../../auth/verify')
const verifyRequestMethod = require('../../tool/verifyRequestMethod')

/**
 * @description 获取文章列表
 */
module.exports = function () {
    const that = this
    /**
     * @description 获取query
     * @type {{}|*}
     */
    const query = this.getQueryData(this.request.url)
    /**
     * @description 组装翻页数据
     * @type {{}}
     */
    const pages = this.setPagination(query.currentPage, query.pageSize)
    /**
     * @description 授权
     */
    const authorization = this.request.headers.authorization
    /**
     * @description 请求验证
     */
    verifyRequestMethod(this.request, 'GET').then(function () {
        /**
         * @description 授权验证
         */
        if (that.isDef(authorization)) {
            return verify(authorization)
        } else {
            return Promise.reject(new Error('缺少Authorization！'))
        }
    }).then(function (data) {
        if (data.type === 3) {
            /**
             * @description 查询条数
             */
            return dataBase.connect(sql.SQL_SELECT_ALL_ARTICLE_COUNT())
        } else {
            return Promise.reject(new Error('您权限不足，请联系管理员！'))
        }
    }).then(function (result) {
        /**
         * @description 总数
         */
        const total = result[0]['COUNT(*)']
        /**
         * @description 查询
         */
        return dataBase.connect(sql.SQL_SELECT_ALL_ARTICLE(pages.pageSize, pages.currentPage)).then(function (result) {
            return Promise.resolve({
                list: result,
                total: total
            })
        })
    }).then(function (data) {
        /**
         * @description 返回数据
         */
        that.response.outPrintData({
            total: data.total,
            list: data.list,
            currentPage: pages.currentPage,
            pageSize: pages.pageSize
        }, '查询成功！')
    }).catch(function (e) {
        that.response.outPrintError((e && e.message) || '未知错误！')
    })
}